package com.restaurant.ressys.controller;

import com.restaurant.ressys.entity.Cart;
import com.restaurant.ressys.entity.CartItem;
import com.restaurant.ressys.entity.Food;
import com.restaurant.ressys.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private FoodService fs;
    @GetMapping("/putCart/{bid}")
    public Cart putCart(@PathVariable("bid") int bid, HttpSession session){
        Cart cart=(Cart)session.getAttribute("cart");
        if(cart==null){
            //没有cart对象
            cart=new Cart();
            Map<Integer, CartItem> buyMap = cart.getBuyMap();
            //从数据库里面查出book对象
            Food food = fs.getById(bid);
            CartItem ci=new CartItem(food,1);
            buyMap.put(bid,ci);
        }else{
            Map<Integer, CartItem> buyMap = cart.getBuyMap();
            if(buyMap.containsKey(bid)){
                //图书在cart购物车里面
                CartItem ci = buyMap.get(bid);
                ci.setCount(ci.getCount()+1);
            }else{
                //从数据库里面查出book对象
                Food food = fs.getById(bid);
                CartItem ci=new CartItem(food,1);
                buyMap.put(bid,ci);
            }
        }
        calMoney(cart);

        session.setAttribute("cart",cart);
        return cart;
    }
    @GetMapping("/myCart")
    public Cart selectMyCart(HttpSession session){
        Cart cart = (Cart)session.getAttribute("cart");
        return cart;
    }
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id")int id,HttpSession session){
        Cart cart=(Cart)session.getAttribute("cart");
        cart.getBuyMap().remove(id);
        calMoney(cart);
    }
    //计算购物车里面的节省金额和总金额
    private void calMoney(Cart cart) {
        //计算总金额
        Map<Integer, CartItem> buyMap = cart.getBuyMap();
        //遍历map集合
        Collection<CartItem> values = buyMap.values();
        double saveMoney = 0;
        double totalMoney = 0;
        for(CartItem ci:values){
            int count = ci.getCount();
            double price = ci.getFood().getPrice();
            totalMoney+=price*count;
        }
        cart.setTotalMoney(totalMoney);
    }
}
